home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / samba.idb / usr / samba / src / source / ubiqx / ubi_SplayTree.c.z / ubi_SplayTree.c
Encoding:
C/C++ Source or Header  |  1998-10-28  |  19.5 KB  |  469 lines

  1. /* ========================================================================== **
  2.  *                              ubi_SplayTree.c
  3.  *
  4.  *  Copyright (C) 1993-1995 by Christopher R. Hertel
  5.  *
  6.  *  Email: crh@ubiqx.mn.org
  7.  * -------------------------------------------------------------------------- **
  8.  *
  9.  *  This module implements "splay" trees.  Splay trees are binary trees
  10.  *  that are rearranged (splayed) whenever a node is accessed.  The
  11.  *  splaying process *tends* to make the tree bushier (improves balance),
  12.  *  and the nodes that are accessed most frequently *tend* to be closer to
  13.  *  the top.
  14.  *
  15.  *  References: "Self-Adjusting Binary Search Trees", by Daniel Sleator and
  16.  *              Robert Tarjan.  Journal of the Association for Computing
  17.  *              Machinery Vol 32, No. 3, July 1985 pp. 652-686
  18.  *
  19.  * -------------------------------------------------------------------------- **
  20.  *
  21.  *  This library is free software; you can redistribute it and/or
  22.  *  modify it under the terms of the GNU Library General Public
  23.  *  License as published by the Free Software Foundation; either
  24.  *  version 2 of the License, or (at your option) any later version.
  25.  *
  26.  *  This library is distributed in the hope that it will be useful,
  27.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  28.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  29.  *  Library General Public License for more details.
  30.  *
  31.  *  You should have received a copy of the GNU Library General Public
  32.  *  License along with this library; if not, write to the Free
  33.  *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  34.  *
  35.  * -------------------------------------------------------------------------- **
  36.  *
  37.  * Log: ubi_SplayTree.c,v
  38.  * Revision 2.6  1997/12/23 04:01:12  crh
  39.  * In this version, all constants & macros defined in the header file have
  40.  * the ubi_tr prefix.  Also cleaned up anything that gcc complained about
  41.  * when run with '-pedantic -fsyntax-only -Wall'.
  42.  *
  43.  * Revision 2.5  1997/07/26 04:15:42  crh
  44.  * + Cleaned up a few minor syntax annoyances that gcc discovered for me.
  45.  * + Changed ubi_TRUE and ubi_FALSE to ubi_trTRUE and ubi_trFALSE.
  46.  *
  47.  * Revision 2.4  1997/06/03 04:42:21  crh
  48.  * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid causing
  49.  * problems.
  50.  *
  51.  * Revision 2.3  1995/10/03 22:19:07  CRH
  52.  * Ubisized!
  53.  * Also, added the function ubi_sptSplay().
  54.  *
  55.  * Revision 2.1  95/03/09  23:54:42  CRH
  56.  * Added the ModuleID static string and function.  These modules are now
  57.  * self-identifying.
  58.  * 
  59.  * Revision 2.0  95/02/27  22:34:46  CRH
  60.  * This module was updated to match the interface changes made to the
  61.  * ubi_BinTree module.  In particular, the interface to the Locate() function
  62.  * has changed.  See ubi_BinTree for more information on changes and new
  63.  * functions.
  64.  *
  65.  * The revision number was also upped to match ubi_BinTree.
  66.  *
  67.  * Revision 1.1  93/10/18  20:35:16  CRH
  68.  * I removed the hard-coded logical device names from the include file
  69.  * specifications.  CRH
  70.  *
  71.  * Revision 1.0  93/10/15  23:00:15  CRH
  72.  * With this revision, I have added a set of #define's that provide a single,
  73.  * standard API to all existing tree modules.  Until now, each of the three
  74.  * existing modules had a different function and typedef prefix, as follows:
  75.  *
  76.  *       Module        Prefix
  77.  *     ubi_BinTree     ubi_bt
  78.  *     ubi_AVLtree     ubi_avl
  79.  *     ubi_SplayTree   ubi_spt
  80.  *
  81.  * To further complicate matters, only those portions of the base module
  82.  * (ubi_BinTree) that were superceeded in the new module had the new names.
  83.  * For example, if you were using ubi_AVLtree, the AVL node structure was
  84.  * named "ubi_avlNode", but the root structure was still "ubi_btRoot".  Using
  85.  * SplayTree, the locate function was called "ubi_sptLocate", but the next
  86.  * and previous functions remained "ubi_btNext" and "ubi_btPrev".
  87.  *
  88.  * This was not too terrible if you were familiar with the modules and knew
  89.  * exactly which tree model you wanted to use.  If you wanted to be able to
  90.  * change modules (for speed comparisons, etc), things could get messy very
  91.  * quickly.
  92.  *
  93.  * So, I have added a set of defined names that get redefined in any of the
  94.  * descendant modules.  To use this standardized interface in your code,
  95.  * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
  96.  * "ubi_tr".  The "ubi_tr" names will resolve to the correct function or
  97.  * datatype names for the module that you are using.  Just remember to
  98.  * include the header for that module in your program file.  Because these
  99.  * names are handled by the preprocessor, there is no added run-time
  100.  * overhead.
  101.  *
  102.  * Note that the original names do still exist, and can be used if you wish
  103.  * to write code directly to a specific module.  This should probably only be
  104.  * done if you are planning to implement a new descendant type, such as
  105.  * red/black trees.  CRH
  106.  *
  107.  * Revision 0.1  93/04/25  22:03:32  CRH
  108.  * Simply changed the <exec/types.h> #include reference the .c file to
  109.  * use <stdlib.h> instead.  The latter is portable, the former is not.
  110.  *
  111.  * Revision 0.0  93/04/21  23:05:52  CRH
  112.  * Initial version, written by Christopher R. Hertel.
  113.  * This module implements Splay Trees using the ubi_BinTree module as a basis.
  114.  *
  115.  * ========================================================================== **
  116.  */
  117.  
  118. #include <stdlib.h>        /* Defines NULL for us.                */
  119. #include "ubi_SplayTree.h" /* Header for THIS module.             */
  120.  
  121. /* ========================================================================== **
  122.  * Static data.
  123.  */
  124.  
  125. static char ModuleID[] = "ubi_SplayTree\n\
  126. \tRevision: 2.6\n\
  127. \tDate: 1997/12/23 04:01:12\n\
  128. \tAuthor: crh\n";
  129.  
  130.  
  131. /* ========================================================================== **
  132.  * Private functions...
  133.  */
  134.  
  135. static void Rotate( ubi_btNodePtr p )
  136.   /* ------------------------------------------------------------------------ **
  137.    * This function performs a single rotation, moving node *p up one level
  138.    * in the tree.
  139.    *
  140.    *  Input:    p - a pointer to an ubi_btNode in a tree.
  141.    *
  142.    *  Output:   None.
  143.    *
  144.    *  Notes:    This implements a single rotation in either direction (left
  145.    *            or right).  This is the basic building block of all splay
  146.    *            tree rotations.
  147.    * ------------------------------------------------------------------------ **
  148.    */
  149.   {
  150.   ubi_btNodePtr parentp;
  151.   ubi_btNodePtr tmp;
  152.   char          way;
  153.   char          revway;
  154.  
  155.   parentp = p->Link[ubi_trPARENT];    /* Find parent. */
  156.  
  157.   if( parentp )                 /* If no parent, then we're already the root. */
  158.     {
  159.     way    = p->gender;
  160.     revway = ubi_trRevWay(way);
  161.     tmp    = p->Link[(int)revway];
  162.  
  163.     parentp->Link[(int)way] = tmp;
  164.     if( tmp )
  165.       {
  166.       tmp->Link[ubi_trPARENT] = parentp;
  167.       tmp->gender             = way;
  168.       }
  169.  
  170.     tmp                   = parentp->Link[ubi_trPARENT];
  171.     p->Link[ubi_trPARENT] = tmp;
  172.     p->gender             = parentp->gender;
  173.     if( tmp )
  174.       tmp->Link[(int)(p->gender)] = p;
  175.  
  176.     parentp->Link[ubi_trPARENT] = p;
  177.     parentp->gender             = revway;
  178.     p->Link[(int)revway]        = parentp;
  179.     }
  180.   } /* Rotate */
  181.  
  182. static ubi_btNodePtr Splay( ubi_btNodePtr SplayWithMe )
  183.   /* ------------------------------------------------------------------------ **
  184.    * Move the node indicated by SplayWithMe to the root of the tree by
  185.    * splaying the tree.
  186.    *
  187.    *  Input:  SplayWithMe - A pointer to an ubi_btNode within a tree.
  188.    *
  189.    *  Output: A pointer to the root of the splay tree (i.e., the same as
  190.    *          SplayWithMe).
  191.    * ------------------------------------------------------------------------ **
  192.    */
  193.   {
  194.   ubi_btNodePtr parent;
  195.  
  196.   while( (parent = SplayWithMe->Link[ubi_trPARENT]) )
  197.     {
  198.     if( parent->gender == SplayWithMe->gender )       /* Zig-Zig */
  199.       Rotate( parent );
  200.     else
  201.       {
  202.       if( ubi_trEQUAL != parent->gender )             /* Zig-Zag */
  203.         Rotate( SplayWithMe );
  204.       }
  205.     Rotate( SplayWithMe );                            /* Zig */
  206.     } /* while */
  207.   return( SplayWithMe );
  208.   } /* Splay */
  209.  
  210. /* ========================================================================== **
  211.  * Exported utilities.
  212.  */
  213.  
  214. ubi_trBool ubi_sptInsert( ubi_btRootPtr  RootPtr,
  215.                           ubi_btNodePtr  NewNode,
  216.                           ubi_btItemPtr  ItemPtr,
  217.                           ubi_btNodePtr *OldNode )
  218.   /* ------------------------------------------------------------------------ **
  219.    * This function uses a non-recursive algorithm to add a new element to the
  220.    * splay tree.
  221.    *
  222.    *  Input:   RootPtr  -  a pointer to the ubi_btRoot structure that indicates
  223.    *                       the root of the tree to which NewNode is to be added.
  224.    *           NewNode  -  a pointer to an ubi_btNode structure that is NOT
  225.    *                       part of any tree.
  226.    *           ItemPtr  -  A pointer to the sort key that is stored within
  227.    *                       *NewNode.  ItemPtr MUST point to information stored
  228.    *                       in *NewNode or an EXACT DUPLICATE.  The key data
  229.    *                       indicated by ItemPtr is used to place the new node
  230.    *                       into the tree.
  231.    *           OldNode  -  a pointer to an ubi_btNodePtr.  When searching
  232.    *                       the tree, a duplicate node may be found.  If
  233.    *                       duplicates are allowed, then the new node will
  234.    *                       be simply placed into the tree.  If duplicates
  235.    *                       are not allowed, however, then one of two things
  236.    *                       may happen.
  237.    *                       1) if overwritting *is not* allowed, this
  238.    *                          function will return FALSE (indicating that
  239.    *                          the new node could not be inserted), and
  240.    *                          *OldNode will point to the duplicate that is
  241.    *                          still in the tree.
  242.    *                       2) if overwritting *is* allowed, then this
  243.    *                          function will swap **OldNode for *NewNode.
  244.    *                          In this case, *OldNode will point to the node
  245.    *                          that was removed (thus allowing you to free
  246.    *                          the node).
  247.    *                          **  If you are using overwrite mode, ALWAYS  **
  248.    *                          ** check the return value of this parameter! **
  249.    *                 Note: You may pass NULL in this parameter, the
  250.    *                       function knows how to cope.  If you do this,
  251.    *                       however, there will be no way to return a
  252.    *                       pointer to an old (ie. replaced) node (which is
  253.    *                       a problem if you are using overwrite mode).
  254.    *
  255.    *  Output:  a boolean value indicating success or failure.  The function
  256.    *           will return FALSE if the node could not be added to the tree.
  257.    *           Such failure will only occur if duplicates are not allowed,
  258.    *           nodes cannot be overwritten, AND a duplicate key was found
  259.    *           within the tree.
  260.    * ------------------------------------------------------------------------ **
  261.    */
  262.   {
  263.   ubi_btNodePtr OtherP;
  264.  
  265.   if( !(OldNode) )
  266.     OldNode = &OtherP;
  267.  
  268.   if( ubi_btInsert( RootPtr, NewNode, ItemPtr, OldNode ) )
  269.     {
  270.     RootPtr->root = Splay( NewNode );
  271.     return( ubi_trTRUE );
  272.     }
  273.  
  274.   /* Splay the unreplacable, duplicate keyed, unique, old node. */
  275.   RootPtr->root = Splay( (*OldNode) );
  276.   return( ubi_trFALSE );
  277.   } /* ubi_sptInsert */
  278.  
  279. ubi_btNodePtr ubi_sptRemove( ubi_btRootPtr RootPtr, ubi_btNodePtr DeadNode )
  280.   /* ------------------------------------------------------------------------ **
  281.    * This function removes the indicated node from the tree.
  282.    *
  283.    *  Input:   RootPtr  -  A pointer to the header of the tree that contains
  284.    *                       the node to be removed.
  285.    *           DeadNode -  A pointer to the node that will be removed.
  286.    *
  287.    *  Output:  This function returns a pointer to the node that was removed
  288.    *           from the tree (ie. the same as DeadNode).
  289.    *
  290.    *  Note:    The node MUST be in the tree indicated by RootPtr.  If not,
  291.    *           strange and evil things will happen to your trees.
  292.    * ------------------------------------------------------------------------ **
  293.    */
  294.   {
  295.   ubi_btNodePtr p;
  296.  
  297.   (void)Splay( DeadNode );                  /* Move dead node to root.        */
  298.   if( (p = DeadNode->Link[ubi_trLEFT]) )    /* If left subtree exists...      */
  299.     {
  300.     ubi_btNodePtr q = DeadNode->Link[ubi_trRIGHT];
  301.  
  302.     p->Link[ubi_trPARENT] = NULL;           /* Left subtree node becomes root.*/
  303.     p->gender             = ubi_trPARENT;
  304.     p                     = ubi_btLast( p );  /* Find rightmost left node...  */
  305.     p->Link[ubi_trRIGHT]  = q;                /* ...attach right tree.        */
  306.     if( q )
  307.       q->Link[ubi_trPARENT] = p;
  308.     RootPtr->root   = Splay( p );           /* Resplay at p.                  */
  309.     }
  310.   else
  311.     {
  312.     if( (p = DeadNode->Link[ubi_trRIGHT]) ) /* No left, but right subtree...  */
  313.       {                                     /* ...exists...                   */
  314.       p->Link[ubi_trPARENT] = NULL;         /* Right subtree root becomes...  */
  315.       p->gender       = ubi_trPARENT;       /* ...overall tree root.          */
  316.       RootPtr->root   = p;
  317.       }
  318.     else
  319.       RootPtr->root = NULL;                 /* No subtrees => empty tree.     */
  320.     }
  321.  
  322.   (RootPtr->count)--;                       /* Decrement node count.          */
  323.   return( DeadNode );                       /* Return pointer to pruned node. */
  324.   } /* ubi_sptRemove */
  325.  
  326. ubi_btNodePtr ubi_sptLocate( ubi_btRootPtr RootPtr,
  327.                              ubi_btItemPtr FindMe,
  328.                              ubi_trCompOps CompOp )
  329.   /* ------------------------------------------------------------------------ **
  330.    * The purpose of ubi_btLocate() is to find a node or set of nodes given
  331.    * a target value and a "comparison operator".  The Locate() function is
  332.    * more flexible and (in the case of trees that may contain dupicate keys)
  333.    * more precise than the ubi_btFind() function.  The latter is faster,
  334.    * but it only searches for exact matches and, if the tree contains
  335.    * duplicates, Find() may return a pointer to any one of the duplicate-
  336.    * keyed records.
  337.    *
  338.    *  Input:
  339.    *     RootPtr  -  A pointer to the header of the tree to be searched.
  340.    *     FindMe   -  An ubi_btItemPtr that indicates the key for which to
  341.    *                 search.
  342.    *     CompOp   -  One of the following:
  343.    *                    CompOp     Return a pointer to the node with
  344.    *                    ------     ---------------------------------
  345.    *                   ubi_trLT - the last key value that is less
  346.    *                              than FindMe.
  347.    *                   ubi_trLE - the first key matching FindMe, or
  348.    *                              the last key that is less than
  349.    *                              FindMe.
  350.    *                   ubi_trEQ - the first key matching FindMe.
  351.    *                   ubi_trGE - the first key matching FindMe, or the
  352.    *                              first key greater than FindMe.
  353.    *                   ubi_trGT - the first key greater than FindMe.
  354.    *  Output:
  355.    *     A pointer to the node matching the criteria listed above under
  356.    *     CompOp, or NULL if no node matched the criteria.
  357.    *
  358.    *  Notes:
  359.    *     In the case of trees with duplicate keys, Locate() will behave as
  360.    *     follows:
  361.    *
  362.    *     Find:  3                       Find: 3
  363.    *     Keys:  1 2 2 2 3 3 3 3 3 4 4   Keys: 1 1 2 2 2 4 4 5 5 5 6
  364.    *                  ^ ^         ^                   ^ ^
  365.    *                 LT EQ        GT                 LE GE
  366.    *
  367.    *     That is, when returning a pointer to a node with a key that is LESS
  368.    *     THAN the target key (FindMe), Locate() will return a pointer to the
  369.    *     LAST matching node.
  370.    *     When returning a pointer to a node with a key that is GREATER
  371.    *     THAN the target key (FindMe), Locate() will return a pointer to the
  372.    *     FIRST matching node.
  373.    *
  374.    *  See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
  375.    * ------------------------------------------------------------------------ **
  376.    */
  377.   {
  378.   ubi_btNodePtr p;
  379.  
  380.   p = ubi_btLocate( RootPtr, FindMe, CompOp );
  381.   if( p )
  382.     RootPtr->root = Splay( p );
  383.   return( p );
  384.   } /* ubi_sptLocate */
  385.  
  386. ubi_btNodePtr ubi_sptFind( ubi_btRootPtr RootPtr,
  387.                            ubi_btItemPtr FindMe )
  388.   /* ------------------------------------------------------------------------ **
  389.    * This function performs a non-recursive search of a tree for any node
  390.    * matching a specific key.
  391.    *
  392.    *  Input:
  393.    *     RootPtr  -  a pointer to the header of the tree to be searched.
  394.    *     FindMe   -  a pointer to the key value for which to search.
  395.    *
  396.    *  Output:
  397.    *     A pointer to a node with a key that matches the key indicated by
  398.    *     FindMe, or NULL if no such node was found.
  399.    *
  400.    *  Note:   In a tree that allows duplicates, the pointer returned *might
  401.    *          not* point to the (sequentially) first occurance of the
  402.    *          desired key.  In such a tree, it may be more useful to use
  403.    *          ubi_sptLocate().
  404.    * ------------------------------------------------------------------------ **
  405.    */
  406.   {
  407.   ubi_btNodePtr p;
  408.  
  409.   p = ubi_btFind( RootPtr, FindMe );
  410.   if( p )
  411.     RootPtr->root = Splay( p );
  412.   return( p );
  413.   } /* ubi_sptFind */
  414.  
  415. void ubi_sptSplay( ubi_btRootPtr RootPtr,
  416.                    ubi_btNodePtr SplayMe )
  417.   /* ------------------------------------------------------------------------ **
  418.    *  This function allows you to splay the tree at a given node, thus moving
  419.    *  the node to the top of the tree.
  420.    *
  421.    *  Input:
  422.    *     RootPtr  -  a pointer to the header of the tree to be splayed.
  423.    *     SplayMe  -  a pointer to a node within the tree.  This will become
  424.    *                 the new root node.
  425.    *  Output: None.
  426.    *
  427.    *  Notes:  This is an uncharacteristic function for this group of modules
  428.    *          in that it provides access to the internal balancing routines,
  429.    *          which would normally be hidden.
  430.    *          Splaying the tree will not damage it (assuming that I've done
  431.    *          *my* job), but there is overhead involved.  I don't recommend
  432.    *          that you use this function unless you understand the underlying
  433.    *          Splay Tree principles involved.
  434.    * ------------------------------------------------------------------------ **
  435.    */
  436.   {
  437.   RootPtr->root = Splay( SplayMe );
  438.   } /* ubi_sptSplay */
  439.  
  440. int ubi_sptModuleID( int size, char *list[] )
  441.   /* ------------------------------------------------------------------------ **
  442.    * Returns a set of strings that identify the module.
  443.    *
  444.    *  Input:  size  - The number of elements in the array <list>.
  445.    *          list  - An array of pointers of type (char *).  This array
  446.    *                  should, initially, be empty.  This function will fill
  447.    *                  in the array with pointers to strings.
  448.    *  Output: The number of elements of <list> that were used.  If this value
  449.    *          is less than <size>, the values of the remaining elements are
  450.    *          not guaranteed.
  451.    *
  452.    *  Notes:  Please keep in mind that the pointers returned indicate strings
  453.    *          stored in static memory.  Don't free() them, don't write over
  454.    *          them, etc.  Just read them.
  455.    * ------------------------------------------------------------------------ **
  456.    */
  457.   {
  458.   if( size > 0 )
  459.     {
  460.     list[0] = ModuleID;
  461.     if( size > 1 )
  462.       return( 1 + ubi_btModuleID( --size, &(list[1]) ) );
  463.     return( 1 );
  464.     }
  465.   return( 0 );
  466.   } /* ubi_sptModuleID */
  467.  
  468. /* ================================ The End ================================= */
  469.